//
//  common.h
//
//  Created by 周凯 on 15/7/16.
//  Copyright (c) 2015年 zk. All rights reserved.
//

#ifndef __common_h__
#define __common_h__

#if defined(__cplusplus)
  #if !defined(__BEGIN_DECLS)
  #define __BEGIN_DECLS		extern "C" {
  #define __END_DECLS		}
#endif
#else
  #define __BEGIN_DECLS
  #define __END_DECLS
#endif

#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>

/** 平台检测*/
#if !defined(__LINUX__) && (defined(__linux__) || defined(__KERNEL__) \
	|| defined(_LINUX) || defined(LINUX) || defined(__linux))
  #define  __LINUX__    (1)
#elif !defined(__APPLE__) && (defined(__MacOS__) || defined(__apple__))
  #define  __APPLE__    (1)
#elif !defined(__CYGWIN__) && (defined(__CYGWIN32__) || defined(CYGWIN))
  #define  __CYGWIN__   (1)
#elif !defined(__WINDOWS__) && (defined(_WIN32) || defined(WIN32) \
	|| defined(_window_) || defined(_WIN64) || defined(WIN64))
  #define __WINDOWS__   (1)
#elif !(defined(__LINUX__) || defined(__APPLE__) \
  || defined(__CYGWIN__) || defined(__WINDOWS__))
  #error "`not support this platform`"
#endif

#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)

/**逻辑跳转优化*/
#if GCC_VERSION
/**条件大多数为真，与if配合使用，直接执行if中语句*/
  #define likely(x)     __builtin_expect(!!(x), 1)
/**条件大多数为假，与if配合使用，直接执行else中语句*/
  #define unlikely(x)   __builtin_expect(!!(x), 0)
#else
  #define likely(x)     (!!(x))
  #define unlikely(x)   (!!(x))
#endif

#ifndef __WINDOWS__
  #include <errno.h>
#else
  #include <process.h>
  #include <Ws2tcpip.h>
  #include <winsock2.h>
  #include <windows.h>
#endif

#include <setjmp.h>
#include <sys/types.h>

#if !defined(STMT_BEGIN) && !defined(STMT_END)
  #define STMT_BEGIN	do {
  #define STMT_END		}while (0)
#endif

#ifndef HAVE_SIGLONGJMP
  #define sigsetjmp(x, y) setjmp((x))
  #define siglongjmp(x, y) longjmp((x), (y))
  typedef jmp_buf sigjmp_buf;
#endif

#if HAS_CXX11_THREAD_LOCAL
  #define THREAD_LOCAL  thread_local
  #define THREAD_LOCAL_DYINIT (1)
#elif GCC_VERSION
  #define THREAD_LOCAL  __thread
  #define THREAD_LOCAL_DYINIT (0)
#elif _MSC_VER
  #define THREAD_LOCAL  __declspec(thread)
  #define THREAD_LOCAL_DYINIT (0)
#else
  #error "`define a thread local storage qualifier for your compiler/platform!`"
#endif

#endif
